using System.Linq;
using Provausio.Common.Objects;
using TrainingManagement.api.Models.BusinessObjects;
using TrainingManagement.api.Models.Data.CRUD;
using TrainingManagement.api.Models.Data.CRUD.SkillSet;

namespace TrainingManagement.api.Models.BusinessLogic.SkillSet
{
    public class SkillSetUpdateItemsOperation : BusinessOperation<BusinessObjects.SkillSet, BusinessObjects.SkillSet>
    {
        readonly SkillSetItemsInsertDataSource _setItemsInsert = new SkillSetItemsInsertDataSource();
        readonly SkillSetSelectOperation _skillSetSelect = new SkillSetSelectOperation();
        readonly SkillSetItemDeleteDataSource _itemDelete = new SkillSetItemDeleteDataSource();

        public override BusinessObjects.SkillSet Run(BusinessObjects.SkillSet input)
        {
            //delete all items from skill set
            _itemDelete.Execute(new SkillSetItemDto {SkillSetId = input.SkillSetId, SkillId = null});

            //reapply items list
            return _setItemsInsert.Execute(input) 
                ? _skillSetSelect.Run(input.SkillSetId).FirstOrDefault() 
                : input;
        }
    }
}